package pgpchat;

import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;

import pgpchat.pgp.PGPActor;

public class ChatPanel extends JFrame {

	private JPanel contentPane;
	private ServerSocket servidor;
	private Socket client;
	public MessageActor mactor;
	public JTextArea txtMsg;
	public JTextArea txtConversa;
	public String login;
	public String senha;
	private PGPActor clientPGP;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					ChatPanel frame = new ChatPanel();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ChatPanel() {
		initializeInterface("teste");
	}

	/**
	 * 
	 */
	private void initializeInterface(String login) {
		this.setVisible(true);
		setTitle("..::PGP chat::..  login: " + login);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 961, 506);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setBounds(72, 294, 416, 100);
		contentPane.add(scrollPane);

		txtMsg = new JTextArea();
		scrollPane.setViewportView(txtMsg);

		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane_1.setBounds(72, 59, 416, 194);
		contentPane.add(scrollPane_1);

		txtConversa = new JTextArea();
		scrollPane_1.setViewportView(txtConversa);
		txtConversa.setEditable(false);

		JScrollPane scrollPane_2 = new JScrollPane();
		scrollPane_2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane_2.setBounds(512, 59, 423, 335);
		contentPane.add(scrollPane_2);

		JTextArea txtConsole = new JTextArea();
		scrollPane_2.setViewportView(txtConsole);
		txtConsole.setEditable(false);

		JButton btnEnviar = new JButton("Enviar");
		btnEnviar.addMouseListener(enviarmsg());
		btnEnviar.setBounds(399, 405, 89, 23);
		contentPane.add(btnEnviar);

		JLabel lblNewLabel = new JLabel("Mensagem");
		lblNewLabel.setBounds(72, 275, 77, 14);
		contentPane.add(lblNewLabel);

		JLabel lblNewLabel_1 = new JLabel("Conversa");
		lblNewLabel_1.setBounds(72, 41, 101, 14);
		contentPane.add(lblNewLabel_1);

		JLabel lblNewLabel_2 = new JLabel("Console");
		lblNewLabel_2.setBounds(512, 41, 112, 14);
		contentPane.add(lblNewLabel_2);
		redirectConsoleTo(txtConsole);
	}

	private void redirectConsoleTo(final JTextArea textarea) {
		PrintStream out = new PrintStream(new ByteArrayOutputStream() {
			@Override
			public synchronized void flush() throws IOException {
				textarea.setText(toString());
			}
		}, true);

		System.setErr(out);
		System.setOut(out);
	}

	/**
	 * @return
	 */
	private MouseAdapter enviarmsg() {
		return new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				String msg = ChatPanel.this.txtMsg.getText();
				ChatPanel.this.mactor.send(msg);
				ChatPanel.this.txtMsg.setText("");
			}
		};
	}

	public ChatPanel(String login, String senha, int porta) {
		this.login = login;
		this.senha = senha;
		AguardandoDialog d = new AguardandoDialog();
		AwaytingCliente worker = null;
		clientPGP = new PGPActor();
		try {
			this.servidor = new ServerSocket(porta);
			worker = new AwaytingCliente(d, this.servidor, this.client, clientPGP);
			worker.execute();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, "Não foi possivel abri conexao");
			e.printStackTrace();
			this.dispose();
		}
		d.setVisible(true);
		initializeInterface(this.login);
		this.client = worker.getClient();

		initializeMsgActor();

	}

	/**
	 * 
	 */
	private void initializeMsgActor() {
		mactor = new MessageActor(this.client, this, clientPGP);
		mactor.start();
	}

	public ChatPanel(String login, String senha, String ip, int porta) {
		this.login = login;
		this.senha = senha;
		System.out.println(senha);
		try {
			this.client = new Socket(ip, porta);
			System.out.println("conectou");
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, "Não foi possível se conectar com este servidor");
			e.printStackTrace();
			this.dispose();
		}
		clientPGP = new PGPActor();
		clientPGP.setReceiverPubKey(PGPHelper.receivePubKey(client));
		PGPHelper.sendKey(clientPGP.getPubKey(), client);

		initializeInterface(this.login);

		initializeMsgActor();
	}
}
